package com.kf.config.shiro;


import com.kf.controller.LoginController;
import com.kf.pojo.*;
import com.kf.pojo.form.UserForm;
import com.kf.service.*;
import com.kf.util.MD5Utils;
import lombok.SneakyThrows;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户领域
 *
 * @author Honey
 * @date 2022/12/17
 */
public class UserRealm extends AuthorizingRealm {

    @Resource
    UserService userService;
    @Resource
    UserRoleService userRoleService;
    @Resource
    RolePermsService rolePermsService;
    @Resource
    PermissionService permissionService;

    @Resource
    RoleService roleService;


    /**
     * 做得到授权信息
     *
     * @param principalCollection 主要收集
     * @return {@link AuthorizationInfo}
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权方法");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();
        int userId = currentUser.getUserId();
        System.out.println(userId);
        //用户角色表  通过当前用户id拿到当前用户-角色这一行数据(可能是多行数据，因为多对多)
        List<UserRole> userRole = userRoleService.getUserRole(userId);
        for (UserRole userrole : userRole) {
            System.out.println("角色id"+userrole.getRoleId());
//            roleService
            Role role = roleService.getRole(userrole.getRoleId());
            info.addRole(role.getName());
            //角色权限表 通过角色id 拿到当前 角色-权限这一行数据(可能是多行数据，因为多对多)
            List<RolePerms> perms = rolePermsService.getPerms(userrole.getRoleId());
            for (RolePerms perm : perms) {
                System.out.println("权限id"+perm.getPermId());
                //权限表 通过权限id 拿到权限这一行数据
                Permission permission = permissionService.getPermsName(perm.getPermId());
                //拿到当前登录用户的角色，并为这个角色赋权
                System.out.println("当前登录的用户的权限"+permission.getPerms());
                info.addStringPermission(permission.getPerms());
            }
        }


        return info;

    }


    /**
     * 做得到身份验证信息
     *
     * @param authenticationToken 身份验证令牌
     * @return {@link AuthenticationInfo}
     * @throws AuthenticationException 身份验证异常
     */
    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证方法");
        UsernamePasswordToken toke= (UsernamePasswordToken)authenticationToken;
        Subject subject = SecurityUtils.getSubject();
        User user = userService.queryUserByName(toke.getUsername());
        UserForm userForm = LoginController.stringThreadLocal.get();
        if(user==null){
            userForm.setStatus(0);
            return null;
        }
        String password = userForm.getPassword();

        if(!MD5Utils.encrypt(user.getUsername(), password).equals(user.getPassword())){
            userForm.setStatus(0);
            return null;
        }
        userForm.setStatus(1);
        System.out.println(user.getPassword());
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);


        System.out.println(user.getUsername());

        return new SimpleAuthenticationInfo(user, password,getName());
    }
    @Override
    public boolean supports(AuthenticationToken authenticationToken) {
        return authenticationToken instanceof UsernamePasswordToken;
    }
}
